package com.central.apps.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.central.app.service.AppCommonService;
import com.central.apps.dao.OverHaulMgDao;
import com.central.apps.entity.*;
import com.central.apps.service.OverhaulMgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.Max;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

@Slf4j
@Service
public class OverHaulMgServiceImpl implements OverhaulMgService {

    @Autowired
    OverHaulMgDao OverHaulMgDao;
    @Autowired
    AppCommonService appCommonService;


    @Override
    public int genInspectionWorkorder(String wonum,String desc,String woType,BlWorkorder BlWorkorder) {
        OverHaulMgDao.insertWorkorderMain(wonum,desc,woType,BlWorkorder);
        return 1;
    }

    @Override
    @Transactional
    public void queryInspectionPlan(String PlanType)  throws Exception{

        BlWorkorder BlWorkorder = new BlWorkorder();

        List<BlInspectionplan> inspareas = OverHaulMgDao.queryInspectionPlan(PlanType);

        List<BlInsparealocation> blInspectlocation = null;
        List<BlInsparealine> BlInspectasset = null;
        List<BlInspectionstandardline> BlInspectionstandardline = null;


        //下次执行时间
        Date nextDate = null;
        Date sysDate = new Date();
        // 周期
        String cycle = "";
        // 频率
        int frequency = 0;
        //最大的工单编号
        String MaxWonum = "";
        // 当前生成的工单ID
        int workorderid = 0;

        String qyNum = "";
        String BZNum = "";
        //计算过后的下次生成日期;
         String upDateNextDate = "";
        for (BlInspectionplan insparea : inspareas) {
            MaxWonum = "";
            nextDate = insparea.getMaintenancenexttime();

            if(nextDate.before(sysDate)){


                upDateNextDate = getNextexDate(nextDate,insparea.getMaintenancecycleunit(),insparea.getInspectioncycle());

               // 获取下一个工单编码
                MaxWonum = quryMaxWonum("巡点检工单","JH-XDJ-");

                BlWorkorder.setStatus("草稿");
                BlWorkorder.setUdwotype("巡点检工单");
                BlWorkorder.setWonum(MaxWonum);
                BlWorkorder.setFixplannum(insparea.getInsstdnum());
                BlWorkorder.setFixplandesc(insparea.getInsstdname());
                BlWorkorder.setInspareacode(insparea.getInsaenum());
                BlWorkorder.setInspareadesc(insparea.getInsaedesc());
                BlWorkorder.setInspareadesc(insparea.getInsaedesc());
                BlWorkorder.setPlannum(insparea.getInspectionid());
                BlWorkorder.setPlandescription(insparea.getDescription());
                BlWorkorder.setDeptcode(insparea.getDeptcode());
                BlWorkorder.setSitecode(insparea.getSitecode());
                BlWorkorder.setOrgcode(insparea.getOrgcode());

                log.info("=====================================insparea:"+ insparea.getInsstdnum()+insparea.getInsaedesc()+insparea.getInsaenum()+insparea.getInsaedesc());

                log.info("=====================================BlWorkorder:"+ BlWorkorder.getFixplannum()+BlWorkorder.getFixplandesc()+BlWorkorder.getInspareacode()+BlWorkorder.getInspareadesc());

                // 新建工单主数据 返回工单ID
                workorderid = genInspectionWorkorder(MaxWonum,insparea.getDescription(),"巡点检工单",BlWorkorder);

               // 获取巡检区域的的位置列表  并插入到工单 位置列表中
                qyNum = quryQyNum((int) insparea.getId());
                blInspectlocation = quryLocationList(qyNum);
                for (BlInsparealocation inspectlocation : blInspectlocation) {
                    insertWoLocation(MaxWonum,inspectlocation.getSeat(),inspectlocation.getLocaEnityDescription());
                    log.info("===========================getInspectioncontent" + inspectlocation.getLocaEnityDescription());
                }
                BlInspectasset = queryAssetList(qyNum);
                for (BlInsparealine blInspectasset : BlInspectasset) {
                    insertWoAsset(MaxWonum,blInspectasset.getInsaeassetnum(),blInspectasset.getAssetEnityDescription());

                    log.info("===========================getInspectioncontent" + blInspectasset.getAssetEnityDescription());
                }


                BZNum = quryBZNum((int) insparea.getId());
                BlInspectionstandardline = quryTaskList(BZNum);
                for (BlInspectionstandardline blInspectionstandardline : BlInspectionstandardline) {
                    insertWoTask(MaxWonum,blInspectionstandardline);

                    log.info("===========================getInspectioncontent" + blInspectionstandardline.getInspectioncontent());
                }

               /* Map<String,Object> workorder = new HashMap<>();
                workorder.put("DESCRIPTION",insparea.getDescription());
                workorder.put("UDWOTYPE","巡点检工单");
                workorder.put("inspareacode",insparea.getInsaenum());
                workorder.put("inspareadesc",insparea.getInsaedesc());
                workorder.put("fixplannum",insparea.getInsstdnum());
                workorder.put("fixplandesc",insparea.getInsaedesc());
                workorder.put("status","草稿");
                qyNum = quryQyNum((int) insparea.getId());
                blInspectlocation = quryLocationList(qyNum);
                BlInspectasset = queryAssetList(qyNum);
                BZNum = quryBZNum((int) insparea.getId());
                BlInspectionstandardline = quryTaskList(BZNum);

                List<Map<String, Object>> BlInspectassetMap = returnLxAssetBean(BlInspectasset);
                List<Map<String, Object>> blInspectlocationMap = returnLxLoationBean(blInspectlocation);
                List<Map<String, Object>> BlInspectionstandardlineMap = returnTaskBean(BlInspectionstandardline);

                Map<String,Object> insertWorkorder = returnWorkorderMain(workorder,BlInspectassetMap,blInspectlocationMap,BlInspectionstandardlineMap);

                appCommonService.saveOrUpdate("inspectionorderApp",insertWorkorder);*/

                //更新下次执行时间
                updateNextTime((int) insparea.getId(),upDateNextDate);
            }

        }



    }


    @Override
    @Transactional
    public void queryJwXPlan(String PlanType)  throws Exception{

        PlanType = "检修";
        BlWorkorder BlWorkorder = new BlWorkorder();

        List<BlInspectionplan> inspareas = OverHaulMgDao.queryInspectionPlan(PlanType);

        List<BlInsparealocation> blInspectlocation = null;
        List<BlInsparealine> BlInspectasset = null;
        List<BlInspectionstandardline> BlInspectionstandardline = null;


        //下次执行时间
        Date nextDate = null;
        Date sysDate = new Date();
        // 周期
        String cycle = "";
        // 频率
        int frequency = 0;
        //最大的工单编号
        String MaxWonum = "";
        // 当前生成的工单ID
        int workorderid = 0;

        String qyNum = "";
        String BZNum = "";
        //计算过后的下次生成日期;
        String upDateNextDate = "";
        for (BlInspectionplan insparea : inspareas) {
            MaxWonum = "";
            nextDate = insparea.getMaintenancenexttime();

            if(nextDate.before(sysDate)){
                log.info("===================exDate: 执行执行！");

                upDateNextDate = getNextexDate(nextDate,insparea.getMaintenancecycleunit(),insparea.getInspectioncycle());

                // 获取下一个工单编码
                MaxWonum = quryMaxWonum("检维修工单","JH-JWX-");

                BlWorkorder.setStatus("草稿");
                BlWorkorder.setUdwotype("检维修工单");
                BlWorkorder.setWonum(MaxWonum);
                BlWorkorder.setFixplannum(insparea.getInspectionid());
                BlWorkorder.setFixplandesc(insparea.getDescription());
                BlWorkorder.setRoutinginspectionstandardcode(insparea.getInsstdnum());
                BlWorkorder.setRoutinginspectionstandarddesc(insparea.getInsstdname());

                BlWorkorder.setInspareacode(insparea.getInsaenum());
                BlWorkorder.setInspareadesc(insparea.getInsaedesc());
                BlWorkorder.setDeptcode(insparea.getDeptcode());
                BlWorkorder.setSitecode(insparea.getSitecode());
                BlWorkorder.setOrgcode(insparea.getOrgcode());

                // 新建工单主数据 返回工单ID
               // workorderid = genInspectionWorkorder(MaxWonum,insparea.getDescription(),"检维修工单",BlWorkorder);
                OverHaulMgDao.insertWorkorderJWXMain(MaxWonum,insparea.getDescription(),"检维修工单",BlWorkorder);

               /* // 获取巡检区域的的位置列表  并插入到工单 位置列表中

                blInspectlocation = quryLocationList(insparea.getInsaenum());
                for (BlInsparealocation inspectlocation : blInspectlocation) {
                    insertWoLocation(MaxWonum,inspectlocation.getSeat(),inspectlocation.getLocaEnityDescription());
                    log.info("===========================getInspectioncontent" + inspectlocation.getLocaEnityDescription());
                }
                BlInspectasset = queryAssetList(insparea.getInsaenum());
                for (BlInsparealine blInspectasset : BlInspectasset) {
                    insertWoAsset(MaxWonum,blInspectasset.getInsaeassetnum(),blInspectasset.getAssetEnityDescription());

                    log.info("===========================getInspectioncontent" + blInspectasset.getAssetEnityDescription());
                }
*/


                BlInspectionstandardline = quryTaskList(insparea.getInsstdnum());
                for (BlInspectionstandardline blInspectionstandardline : BlInspectionstandardline) {
                    insertWoTask(MaxWonum,blInspectionstandardline);

                }



                //更新下次执行时间
                updateNextTime((int) insparea.getId(),upDateNextDate);
            }

        }



    }



    @Override
    public void updateNextTime(int id,String nextDate) {

        OverHaulMgDao.updateNextTime(id,nextDate);
    }

    @Override
    public String getNextexDate(Date exDate,String frequency,String cycle){

        int fre = Integer.parseInt(frequency);
        int unitTime = 0;
        if("D".equals(cycle)){
            unitTime = 1;
        }
        if("W".equals(cycle)){
            unitTime = 7;
        }
        if("M".equals(cycle)){
            unitTime = 30;
        }
        if("Y".equals(cycle)){
            unitTime = 365;
        }

        Calendar ca = Calendar.getInstance();
        ca.setTime(exDate);
        ca.add(Calendar.DAY_OF_MONTH, fre*unitTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return sdf.format(ca.getTime());
    }

    @Override
    public String quryMaxWonum(String woType,String woFax) {
        String nowWonum = OverHaulMgDao.quryMaxWonum(woType);
        if("".equals(nowWonum) || nowWonum==null){
            nowWonum =  "100000";
        }else{
            nowWonum = String.format("%06d",
                    new Object[] {
                            Integer.valueOf(Integer.parseInt(nowWonum.substring(nowWonum.length() - 6)) + 1) });
        }
        nowWonum = woFax + nowWonum;

        return nowWonum;
    }

    @Override
    public String quryQyNum(int id) {
        return OverHaulMgDao.quryQyNum(id);
    }

    @Override
    public List<BlInsparealocation> quryLocationList(String insaenum) {

        return OverHaulMgDao.quryLocationList(insaenum);
    }


    @Override
    public void insertWoLocation(String wonum, String location, String desc) {
        OverHaulMgDao.insertWoLocation(wonum,location,desc);
    }

    @Override
    public List<BlInsparealine> queryAssetList(String insaenum) {
        return OverHaulMgDao.queryAssetList(insaenum);
    }

    @Override
    public void insertWoAsset(String wonum, String assetnum, String desc) {
        OverHaulMgDao.insertWoAsset(wonum,assetnum,desc);
    }

    @Override
    public String quryBZNum(int id) {
        return OverHaulMgDao.quryBZNum(id);
    }

    @Override
    public List<BlInspectionstandardline> quryTaskList(String insaenum) {
        return OverHaulMgDao.quryTaskList(insaenum);
    }

    @Override
    public void insertWoTask(String wonum,BlInspectionstandardline task) {
        OverHaulMgDao.insertWoTask(wonum,task);
    }

    //  根据 路线向工单插入 多资产  多位置
    @Override
    public String insertLxToWorkoder(String wonum, String LxNum) {
        JSONObject json = new JSONObject();
        json.put("code", "0");
        List<BlInsparealocation> blInspectlocation = null;
        List<BlInsparealine> BlInspectasset = null;

        blInspectlocation = quryLocationList(LxNum);
//        for (BlInsparealocation inspectlocation : blInspectlocation) {
//            insertWoLocation(wonum,inspectlocation.getSeat(),inspectlocation.getLocaEnityDescription());
//            log.info("===========================getInspectioncontent" + inspectlocation.getLocaEnityDescription());
//        }
        BlInspectasset = queryAssetList(LxNum);
//        for (BlInsparealine blInspectasset : BlInspectasset) {
//            insertWoAsset(wonum,blInspectasset.getInsaeassetnum(),blInspectasset.getAssetEnityDescription());
//
//            log.info("===========================getInspectioncontent" + blInspectasset.getAssetEnityDescription());
//        }

        json.put("blInspectlocationList", blInspectlocation);
        json.put("BlInspectassetList", BlInspectasset);
        json.put("msg", "插入路线信息完成！");
        return json.toJSONString();
    }

    //  根据 标准编号 向工单插入 工作任务
    @Override
    public String insertTaskToWorkoder(String wonum,String TaskNum) {
        JSONObject json = new JSONObject();
        json.put("code", "0");
        List<BlInspectionstandardline> BlInspectionstandardline = null;


        BlInspectionstandardline = quryTaskList(TaskNum);
        for (BlInspectionstandardline blInspectionstandardline : BlInspectionstandardline) {

            insertWoTask(wonum,blInspectionstandardline);
            log.info("===========================getInspectioncontent" + blInspectionstandardline.getInspectioncontent());
        }
        //json.put("BlInspectionstandardlineList", BlInspectionstandardline);
        json.put("msg", "插入标准信息完成！");
        return json.toJSONString();
    }



    @Override
    public String TestCreate() throws Exception{
        Map<String, Object> workorderSet = new HashMap<>();
        List<Map<String,Object>> BlInspectassetList = new ArrayList<>();

        Map<String,Object> BlInspectasset = new HashMap<>();
        BlInspectasset.put("assetnum","1111111");
        BlInspectasset.put("assetdesc","222222222");

        BlInspectassetList.add(BlInspectasset);

        workorderSet.put("DESCRIPTION","测试saveOrUpdate");

        workorderSet.put("bl_inspectassetList",BlInspectassetList);
        appCommonService.saveOrUpdate("inspectionorderApp",workorderSet);
       // appCommonService.save("inspectionorderApp",workorderSet);

        return "创建成功！";
    }

    @Override
    public List<Map<String, Object>> returnLxLoationBean(List<BlInsparealocation> BlInsparealocation) {
        List<Map<String, Object>>  BlInsparealocationList = new ArrayList<>();
        Map<String,Object> BlInsparealocationMap = new HashMap<>();
        for (BlInsparealocation inspectlocation : BlInsparealocation) {
            BlInsparealocationMap.clear();
            BlInsparealocationMap.put("location",inspectlocation.getSeat());
            BlInsparealocationMap.put("locationdesc",inspectlocation.getLocaEnityDescription());
            BlInsparealocationList.add(BlInsparealocationMap);

        }
        return BlInsparealocationList;
    }

    @Override
    public List<Map<String, Object>> returnLxAssetBean(List<BlInsparealine> BlInsparealine) {
        List<Map<String, Object>>  BlInsparealineList = new ArrayList<>();
        Map<String,Object> BlInsparealineMap = new HashMap<>();
        for (BlInsparealine blInspectasset : BlInsparealine) {
            BlInsparealineMap.clear();
            BlInsparealineMap.put("assetnum",blInspectasset.getInsaeassetnum());
            BlInsparealineMap.put("assetdesc",blInspectasset.getInsaeassetnum());
            BlInsparealineList.add(BlInsparealineMap);
        }


        return BlInsparealineList;
    }

    @Override
    public List<Map<String, Object>> returnTaskBean(List<BlInspectionstandardline> BlInspectionstandardline) {
        List<Map<String, Object>>  BlInspectionstandardlineList = new ArrayList<>();
        Map<String,Object> BlInspectionstandardlineMap = new HashMap<>();
        for (BlInspectionstandardline blInspectionstandardline : BlInspectionstandardline) {
            BlInspectionstandardlineMap.clear();
            BlInspectionstandardlineMap.put("inspectionassetnum",blInspectionstandardline.getInspectionassetnum());
            BlInspectionstandardlineMap.put("inspectionassetname",blInspectionstandardline.getInspectionassetnum());
            BlInspectionstandardlineMap.put("inspectioncontent",blInspectionstandardline.getInspectioncontent());
            BlInspectionstandardlineMap.put("inspectionmethod",blInspectionstandardline.getInspectionmethod());
            BlInspectionstandardlineMap.put("inspectiontool",blInspectionstandardline.getInspectiontool());
            BlInspectionstandardlineMap.put("importantprocedures",blInspectionstandardline.getImportantprocedures());
            BlInspectionstandardlineMap.put("operatingstatus",blInspectionstandardline.getOperatingstatus());
            BlInspectionstandardlineMap.put("inspectionstandard",blInspectionstandardline.getInspectionstandard());
            BlInspectionstandardlineMap.put("part",blInspectionstandardline.getPart());
            BlInspectionstandardlineList.add(BlInspectionstandardlineMap);
        }

        return BlInspectionstandardlineList;
    }

    @Override
    public Map<String, Object> returnWorkorderMain(Map<String, Object> workoder,List<Map<String, Object>> Asset,List<Map<String, Object>> Location,List<Map<String, Object>> Task) {
        workoder.put("bl_inspectassetList",Asset);
        workoder.put("bl_inspectlocation",Location);
        workoder.put("bl_workordertask",Task);

        return workoder;
    }


}
